import router from './router/router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { Message } from "element-ui";
import getPageTitle from './until/get-page-title'
import { getToken }  from './until/auth'
NProgress.configure({ showSpinner: false }) // 进入路由时访问进度条  如果为false则右侧没有等待旋转符号
const whiteList = ['/login', '/auth-redirect']
router.beforeEach(async(to, from, next) => {
    NProgress.start()
    document.title = getPageTitle(to.meta.title) || '管理后台'
    const hasToken = getToken()
    if(hasToken){
        if(to.path === '/login'){
            next({path:'/'})
            NProgress.done()
        }else {
            const hasRoles = store.getters.roles && store.getters.roles.length > 0
            if(hasRoles){
                next()
                NProgress.done()
            }else {
                try {
                    const { roles } = await store.dispatch('user/getInfo') || ['admin']
                    const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
                    router.addRoutes(accessRoutes)
                    // replace 为true时 登录之后到首页回退不会返回登录页面
                    next({ ...to, replace: true })
                    NProgress.done()
                }catch (error) {
                    await store.dispatch('user/resetToken')
                    // Message.error(error || '为获取角色信息，返回登录页')
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }

            }
        }
        console.log("1111")
    }else {

        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
        console.log("2222")
    }
    // const isGetRoutes =  await store.getters.permission_isGetRoutes
    // if(isGetRoutes){
    //     next()
    //     NProgress.done()
    // }else {
    //     await store.dispatch('permission/setIsGetRoutes', true)
    //     const accessRoutes = await store.dispatch('permission/generateRoutes', "edit")
    //     router.addRoutes(accessRoutes)
    //     next({...to})
    //     NProgress.done()
    // }
    // next()
    // NProgress.done()
})

